package tdd.xuchun.test.service.impl;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import cn.hutool.core.util.StrUtil;
import tdd.xuchun.test.model.Host;
import tdd.xuchun.test.util.BizException;
import tdd.xuchun.test.util.HttpUtil;
import tdd.xuchun.test.util.SSH2Util;
import tdd.xuchun.test.util.TarUntil;

@Service("easyNmonService")
public class EasyNmonServiceImpl implements tdd.xuchun.test.service.IEasyNmonService {

    @SuppressWarnings("finally")
    @Override
    // 上传并启动easyNmon
    public boolean upAndRun(Host host, int cover) {
        SSH2Util ssh2Util = null;
        boolean flag = true;
        String nmonzipName = "easyNmon.tar.gz";
        try {
            File fout = TarUntil.getdiskFile("/nmon/" + nmonzipName);
            String localpath = fout.getAbsolutePath().replaceAll(nmonzipName, "");
            //String localpath = new EasyNmonServiceImpl().getClass().getClassLoader().getResource("/").getPath();
            flag = false;
            ssh2Util = SSHConnect(host);
            String path = ssh2Util.runCommand("pwd").replaceAll("info:", "").replaceAll("\n", "");
            String file = ssh2Util.runCommand("ls | grep easyNmon-runner.sh");
            ssh2Util.runCommand("killall -9 easyNmon\npkill -9 nmon*");
            if (cover == 1 || file.indexOf("easyNmon-runner.sh") < 0) {
                ssh2Util.runCommand("rm -rf easyNmon-runner.sh");
                ssh2Util.runCommand("rm -rf easyNmon*");
                ssh2Util.putFile(localpath, nmonzipName, path);

                for (int i = 0; i < 3; i++) {
                    Thread.sleep(1000);
                    String sb = ssh2Util.runCommand("ls");
                    if (sb.contains(nmonzipName)) {
                        break;
                    }
                }
                ssh2Util.runCommand("tar -xvf " + nmonzipName + " && rm -rf " + nmonzipName);
                ssh2Util.putFile(localpath, "nmonanaly.xlsm", path + "/easyNmon/report/");
            }
            ssh2Util.runCommand("echo \"export TZ=GMT-8\ncd easyNmon\" > easyNmon-runner.sh");
            String commtent = "";

            String nout=ssh2Util.runCommand("nmon -q");
            //判读是否已装nmon,如果装了优先走本地安装的
            if( nout.contains("invalid option")){
                commtent = "echo \"killall -9 easyNmon 2>/dev/null\nnohup ./easyNmon -p " + host.getEznmonport() + " -np nmon >/dev/null 2>&1 &\" >> easyNmon-runner.sh";
            }
            else if (StrUtil.isNotEmpty(host.getOstype())) {
                commtent = "echo \"killall -9 easyNmon 2>/dev/null\nnohup ./easyNmon -p " + host.getEznmonport() + " -np ./nmon/nmon_"
                        + host.getOstype().replaceAll("\\s*", "") + " >/dev/null 2>&1 &\" >> easyNmon-runner.sh";

            } else {
                commtent = "echo \"killall -9 easyNmon 2>/dev/null\nnohup ./easyNmon -p " + host.getEznmonport()
                        + " >/dev/null 2>&1 &\" >> easyNmon-runner.sh";
            }
            ssh2Util.runCommand(commtent);
            String str=ssh2Util.runCommand("sh " + path + "/easyNmon-runner.sh");
            flag = true;
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        } finally {
            if (ssh2Util != null) {
                try {
                    ssh2Util.close();
                } catch (Exception e) {
                    throw new BizException(e);
                }
            }
            return flag;
        }

    }

    //执行指令并检查状态码
    @Override
    public int accessTheURL(Host host, String urlSuffix) {
        String url = "http://" + host.getAddr() + ":" + host.getEznmonport() + "/" + urlSuffix;
        return HttpUtil.getStateCode(url);
    }

    @SuppressWarnings("finally")
    @Override
    public boolean clearReport(Host host) {
        SSH2Util ssh2Util = null;
        boolean flag = true;
        try {
            ssh2Util = SSHConnect(host);
            ssh2Util.runCommand("find $PWD/easyNmon/report/* -maxdepth 0 -type d | xargs rm -rf");
            ssh2Util.runCommand("find $PWD/easyNmon/report/* -maxdepth 0 -type f -name *.zip | xargs rm -rf");
        } catch (Exception e) {
            flag = false;
            throw new BizException(e);
        } finally {
            if (ssh2Util != null) {
                try {
                    ssh2Util.close();
                } catch (Exception e) {
                    throw new BizException(e);
                }
            }
            return flag;
        }

    }

    /**
     * 文件夹打包并下载
     */

    @SuppressWarnings("finally")
    @Override
    public boolean getReportPackage(Host host) {
        SSH2Util ssh2Util = null;
        boolean flag = true;
        try {
            ssh2Util = SSHConnect(host);
            ssh2Util.runCommand("find $PWD/easyNmon/report/* -maxdepth 0 -type d | xargs -i basename {} | xargs -i curl \"http://127.0.0.1:" + host.getEznmonport() + "/generate/{}/\" >/dev/null 2>&1");
            ssh2Util.runCommand("find $PWD/easyNmon/report/* -maxdepth 0 -type d | xargs -i sh -c \"echo -n \\\"var reportData=\\\" > {}/data.js && cat {}/data.json >> {}/data.js\"");
            ssh2Util.runCommand("find $PWD/easyNmon/report/* -maxdepth 0 -type f -name *.zip | xargs rm -rf");
            ssh2Util.runCommand("tar -cvf \"$PWD/easyNmon/report/easyNmonReport_" + host.getName() + ".zip\" easyNmon/report/*");
        } catch (Exception e) {
            flag = false;
            throw new BizException(e);
        } finally {
            if (ssh2Util != null) {
                try {
                    ssh2Util.close();
                } catch (Exception e) {
                    throw new BizException(e);
                }
            }
            return flag;
        }
    }

    // 查询easyNmon包中的nmon文件支持的操作系统
    @SuppressWarnings("finally")
    @Override
    public List<String> getEzNmonOS() {
        List<String> fileArray = new ArrayList<String>();

        try {
            File fout = TarUntil.getdiskFile("/nmon/easyNmon.tar.gz");
            List<String> fileNames = TarUntil.visitTARGZ(fout);
            for (int i = 0; i < fileNames.size(); i++) {
                String filetype = (String) fileNames.get(i);
                if (filetype.contains("/nmon/nmon_")) {
                    int begin = filetype.indexOf("nmon_") + 5;
                    fileArray.add(StrUtil.sub(filetype, begin, filetype.length()));
                }
            }

        } catch (IOException e) {
            throw new BizException(e);
        } finally {
            return fileArray;
        }
    }

    @Override
    public boolean clearService(Host host) {
        boolean flag = true;
        SSH2Util ssh2Util = SSHConnect(host);
        try {
            ssh2Util.runCommand("killall -9 easyNmon\npkill -9 nmon*");
            ssh2Util.runCommand("rm -rf easyNmon-runner.sh");
            ssh2Util.runCommand("rm -rf easyNmon*");
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        } finally {
            if (ssh2Util != null) {
                try {
                    ssh2Util.close();
                } catch (Exception e) {
                   // throw new BizException(e);
                    e.printStackTrace();
                }
            }
            return flag;
        }
    }

    private SSH2Util SSHConnect(Host host) {
        SSH2Util ssh2Util = null;
        ssh2Util = new SSH2Util(host.getAddr(), host.getUsername(), host.getKeyfilepath(), host.getPassword(), host.getPort());
        return ssh2Util;
    }


}
